package cn.doitedu.api;

import beans.Student;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class _11_State_First_Demo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        // 从socket读字母  (1,a) (1,b) (2,a) (1,c) (2,b)
        DataStreamSource<String> stream = env.socketTextStream("doitedu", 9999);

        // 且 id 和 字母
        SingleOutputStreamOperator<Tuple2<Integer, String>> tuples = stream.map(new MapFunction<String, Tuple2<Integer, String>>() {
            @Override
            public Tuple2<Integer, String> map(String value) throws Exception {
                String[] split = value.split(",");
                return Tuple2.of(Integer.parseInt(split[0]), split[1]);
            }
        });

        // 按相同id，去进行字母拼接
        KeyedStream<Tuple2<Integer, String>, Integer> keyedStream = tuples.keyBy(tp -> tp.f0);


        keyedStream.map(new RichMapFunction<Tuple2<Integer, String>, String>() {

            ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {

                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("acc", String.class));

            }

            @Override
            public String map(Tuple2<Integer, String> value) throws Exception {

                // 从状态中获取此前拼接的结果
                String accStr = valueState.value();
                accStr = accStr == null ? "" : accStr;

                // 拼接
                accStr = value.f1 + accStr ;

                // 将最新的拼接结果更新到状态
                valueState.update(accStr);


                return value.f0+":"+accStr;
            }
        }).print();


        env.execute();

    }

}
